package com.lambkit.devops.monitor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.lambkit.core.Lambkit;
import com.lambkit.core.LambkitConfig;
import com.lambkit.db.DbPool;
import com.lambkit.db.RowData;
import com.lambkit.devops.DevopsKit;
import com.lambkit.node.LambkitNodeManager;

import java.util.List;
import java.util.Map;


/**
 * 监控任务
 * @author DELL
 *
 */
public class MonitorTask {

	private MonitorApiStatus apiStatus = new MonitorApiStatus();
	
	//private MonitorCache monitorCache
	
	public Map<String,Object> excute(boolean recordApiStatus) {
		// TODO Auto-generated method stub
		String value = DevopsKit.getSetting("lambkit.devops.monitortask");
		if(!"true".equals(value)) {
			return null;
		}
		Map<String,Object> result = MapUtil.newHashMap();
		result.put("type", "devops");
		result.put("name", Lambkit.config(LambkitConfig.class).getName());
		result.put("node", LambkitNodeManager.me().getNode().getId());
		
		//01-服务器监测
		MonitorServer monitorServer = new MonitorServer();
		try {
			monitorServer.build(DevopsKit.getSetting("lambkit.devops.server"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		result.put("server", monitorServer);
		
		//02-健康监测
		String devlopName = DevopsKit.getDatabaseConfigName();
		if (StrUtil.isNotBlank(devlopName)) {
			List<RowData> sysRecords = CollUtil.newArrayList();
			List<RowData> systems = DbPool.use(devlopName).find("select * from devops_system");
			for(RowData system : systems) {
				String curl = system.getStr("curl");
				//健康监测
				int status = apiStatus.apiRequest(curl);
				String code = system.getStr("code");
				RowData record = DbPool.use(devlopName).newRowData();
				record.set("code", code);
				record.set("url", curl);
				record.set("status", status);
				record.set("created", System.currentTimeMillis());//DateTimeUtils.dateToString(new Date())
				if(recordApiStatus) {
					String devopsLog = DevopsKit.getConfig("lambkit.devops.logname");
					if(StrUtil.isNotBlank(devopsLog)) {
						record.setTableName("devops_api_status");
						record.setPrimaryKey("api_status_id");
						DbPool.use(devopsLog).save(record);
					}
				}
				sysRecords.add(record);
			}
			result.put("system", sysRecords);
		}
		
		return result;
	}

	
	
}
